<template>
  <div id="personalMessagePage">
    <h2 class="title">个人信息</h2>
    <a-form 
      :model="formState" 
      name="personalMessage" 
      autocomplete="off"
      @finish="handleSubmit"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
      <a-form-item label="用户头像">
        <div class="avatar-container">
          <a-avatar :size="100" :src="formState.userAvatar" />
          <a-upload
            name="file"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @change="handleAvatarChange"
          >
            <a-button class="upload-btn" type="primary" size="small">更换头像</a-button>
          </a-upload>
        </div>
      </a-form-item>

      <a-form-item 
        label="用户昵称" 
        name="userName"
        :rules="[{ required: true, message: '请输入昵称' }]"
      >
        <a-input v-model:value="formState.userName" placeholder="请输入昵称" />
      </a-form-item>

      <a-form-item label="用户简介" name="userProfile">
        <a-textarea 
          v-model:value="formState.userProfile" 
          placeholder="请输入个人简介" 
          :rows="4" 
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
        <a-button type="primary" html-type="submit" :loading="submitting">保存</a-button>
        <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useLoginUserStore } from '@/stores/loginUser.ts'
import { updateCurrentUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'

const loginUserStore = useLoginUserStore()
const submitting = ref(false)

// 初始化表单数据
const formState = reactive<API.UserUpdateRequest>({
  id: 0,
  userName: '',
  userAvatar: '',
  userProfile: ''
})

// 页面加载时获取当前用户信息
onMounted(async () => {
  await loginUserStore.fetchLoginUser()
  if (loginUserStore.loginUser) {
    formState.id = loginUserStore.loginUser.id
    formState.userName = loginUserStore.loginUser.userName || ''
    formState.userAvatar = loginUserStore.loginUser.userAvatar || ''
    formState.userProfile = loginUserStore.loginUser.userProfile || ''
  }
})

// 处理头像上传
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像变更
const handleAvatarChange = (info: any) => {
  if (info.file.status === 'uploading') {
    return
  }
  if (info.file.status === 'done') {
    // 这里应该从服务器响应中获取图片URL
    // 由于没有具体上传接口，这里使用本地预览URL作为演示
    const reader = new FileReader()
    reader.onload = (e) => {
      formState.userAvatar = e.target?.result as string
    }
    reader.readAsDataURL(info.file.originFileObj)
  }
}

// 提交表单
const handleSubmit = async (values: API.UserUpdateRequest) => {
  submitting.value = true
  try {
    const res = await updateCurrentUser(values)
    if (res.data.code === 0 && res.data.data) {
      message.success('更新成功')
      // 更新store中的用户信息
      await loginUserStore.fetchLoginUser()
    } else {
      message.error('更新失败，' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    message.error('更新失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (loginUserStore.loginUser) {
    formState.userName = loginUserStore.loginUser.userName || ''
    formState.userAvatar = loginUserStore.loginUser.userAvatar || ''
    formState.userProfile = loginUserStore.loginUser.userProfile || ''
  }
}
</script>

<style scoped>
#personalMessagePage {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.upload-btn {
  margin-top: 8px;
}
</style>
